<?php
namespace App\Api\Controllers\In;


use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipayTradeFastpayRefundQueryRequest;
use Alipayopen\Sdk\Request\AlipayTradeQueryRequest;
use Alipayopen\Sdk\Request\AlipayTradeRefundRequest;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use App\Api\Controllers\Config\HConfigController;
use App\Api\Controllers\Config\JdConfigController;
use App\Api\Controllers\Config\LtfConfigController;
use App\Api\Controllers\Config\MyBankConfigController;
use App\Api\Controllers\Config\NewLandConfigController;
use App\Api\Controllers\Config\VbillConfigController;
use App\Api\Controllers\Config\WeixinConfigController;
use App\Api\Controllers\DuoLaBao\ManageController;
use App\Api\Controllers\Merchant\OrderController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Api\Controllers\MyBank\TradePayController;
use App\Api\Controllers\Newland\PayController;
use App\Common\PaySuccessAction;
use App\Common\StoreDayMonthOrder;
use App\Common\UserGetMoney;
use App\Models\AlipayAppOauthUsers;
use App\Models\AlipayIsvConfig;
use App\Models\InCodeList;
use App\Models\InOrder;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Store;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use MyBank\Tools;
use Tymon\JWTAuth\Facades\JWTAuth;

class IndexController extends BaseController
{

    //扫一扫收款
    public function scan_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);


            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }

            $device_no = $data['device_no'];
            $InCodeList = InCodeList::where('device_id', $device_no)
                ->select('config_id', 'merchant_id', 'store_id')
                ->first();

            //需要处理
            $device_no = $data['device_no'];
            $config_id = $InCodeList->config_id;
            $merchant_id = $InCodeList->merchant_id;
            $merchant_name = '';
            $store_id = $InCodeList->store_id;


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'sub_code' => '',
                'sub_msg' => '',
                'pp_trade_no' => $data['pp_trade_no'],
                'transaction_id' => $data['pp_trade_no'],
                'user_order_no' => $data['pp_trade_no'],
                'total_fee' => $data['total_fee'],
                'real_fee' => $data['total_fee'],
                'pay_type' => '',//支付类型
                'time_end' => '',//支付完成时间
                'channel_type' => '',//通道方
            ];

            //请求参数
            $data_re = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'code' => $data['auth_code'],
                'total_amount' => number_format($data['total_fee'] / 100, 2, '.', ''),
                'shop_price' => number_format($data['total_fee'] / 100, 2, '.', ''),
                'device_id' => $device_no,
                'shop_name' => '收款',
                'shop_desc' => '收款',
                'store_id' => $store_id,
                'other_no' => $data['pp_trade_no'],
                'remark' => '',
            ];

            $pay_obj = new PayBaseController();
            $scan_pay_public = $pay_obj->scan_pay_public($data_re);
            $tra_data_arr = json_decode($scan_pay_public, true);
            if ($tra_data_arr['status'] != 1) {
                $re_data['code'] = 'FAIL';
                $re_data['msg'] = $tra_data_arr['message'];
                return $this->return_data($re_data);
            }

            $pay_type = '';
            $ways_source = $tra_data_arr['data']['ways_source'];
            if ($ways_source == "alipay") {
                $pay_type = 'ALIPAY';
            }
            if ($ways_source == "weixin") {
                $pay_type = 'WXPAY';
            }

            if ($ways_source == 'jd') {
                $pay_type = 'JDPAY';
            }
            if ($ways_source == 'unionpay') {
                $pay_type = 'UNIONPAY';
            }

            //意锐入库

            $in_insert = [
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                "device_no" => $device_no,
                "pay_status" => '1',//未付款
                "pay_type" => $pay_type,
                "refund_fee" => '0',
                "total_fee" => $data['total_fee'],
                'pp_trade_no' => $data['pp_trade_no'],
                'out_trade_no' => '',
                "time_end" => '',
                "transaction_id" => '',
            ];


            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {

                //微信，支付宝支付凭证
                $re_data['sub_code'] = 'SUCCESS';
                $re_data['sub_msg'] = '支付成功';
                $re_data['transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['time_end'] = date('Y-m-d H:i:s', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
                $re_data['channel_type'] = $tra_data_arr['data']['ways_source'];
                $re_data['real_fee'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] * 100 : $tra_data_arr['data']['total_amount'] * 100;
                $re_data['pay_type'] = $pay_type;
                $in_insert['pay_status'] = '2';
                $in_insert['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $in_insert['transaction_id'] = $tra_data_arr['data']['trade_no'];
                $in_insert['time_end'] = date('YmdHis', strtotime($re_data['time_end']));


            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['code'] = 'FAIL';
                $re_data['sub_code'] = 'USERPAYING';
                $re_data['sub_msg'] = '用户正在支付';
            } else {
                //其他错误
                $re_data['code'] = 'FAIL';
                $re_data['sub_code'] = 'SYSTEMERROR';
                $re_data['sub_msg'] = $tra_data_arr['message'];
            }


            //意锐
            InOrder::create($in_insert);


            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage().$exception->getLine();
            return $this->return_data($re_data);
        }

    }


    //查询订单号状态
    public function order_query(Request $request)
    {

        try {
            //获取请求参数
            $data = $request->getContent();

            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }
            $device_no = $data['device_no'];
            $InCodeList = InCodeList::where('device_id', $device_no)
                ->select('config_id', 'store_id')
                ->first();
            //需要处理
            $config_id = $InCodeList->config_id;
            $store_id = $InCodeList->store_id;


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'sub_code' => '',
                'sub_msg' => '',
                'pp_trade_no' => $data['pp_trade_no'],
                'transaction_id' => $data['pp_trade_no'],
                'user_order_no' => $data['pp_trade_no'],
                'total_fee' => '',
                'real_fee' => '',
                'pay_type' => '',//支付类型
                'printType' => '0',
                'time_end' => '',//支付完成时间
                'channel_type' => '',//通道方
            ];


            $data_re = [
                'out_trade_no' => '',
                'other_no' => $data['pp_trade_no'],
                'store_id' => $store_id,
                'ways_type' => '',
                'config_id' => $config_id,
            ];


            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($data_re);
            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $re_data['code'] = 'FAIL';
                $re_data['msg'] = $tra_data_arr['message'];
                return $this->return_data($re_data);
            }


            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {

                $pay_type = '';
                $ways_source = $tra_data_arr['data']['ways_source'];
                if ($ways_source == "alipay") {
                    $pay_type = 'ALIPAY';
                }
                if ($ways_source == "weixin") {
                    $pay_type = 'WXPAY';
                }

                if ($ways_source == 'jd') {
                    $pay_type = 'JDPAY';
                }
                if ($ways_source == 'unionpay') {
                    $pay_type = 'UNIONPAY';
                }

                $real_fee = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] * 100 : $tra_data_arr['data']['total_amount'] * 100;
                $total_fee = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] * 100 : $tra_data_arr['data']['total_amount'] * 100;

                //微信，支付宝支付凭证
                $re_data['sub_code'] = 'SUCCESS';
                $re_data['sub_msg'] = '支付成功';
                $re_data['transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['time_end'] = date('Y-m-d H:i:s', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
                $re_data['channel_type'] = $tra_data_arr['data']['ways_source'];
                $re_data['real_fee'] = "" . $real_fee . "";
                $re_data['total_fee'] = "" . $total_fee . "";
                $re_data['pay_type'] = $pay_type;


                //意锐
                $up_data = [
                    'pay_status' => '2',
                    'out_trade_no' => $tra_data_arr['data']['out_trade_no'],
                    'transaction_id' => $tra_data_arr['data']['trade_no'],
                    'time_end' => date('YmdHis', strtotime($re_data['time_end'])),
                ];

                InOrder::where('pp_trade_no', $data['pp_trade_no'])
                    ->where('store_id', $store_id)
                    ->update($up_data);


            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['code'] = 'FAIL';
                $re_data['sub_code'] = 'USERPAYING';
                $re_data['sub_msg'] = '用户正在支付';
                $re_data['real_fee'] = "1";
                $re_data['total_fee'] = "1";
                $re_data['pay_type'] = 'ALIPAY';

            } else {
                //其他错误
                $re_data['code'] = 'FAIL';
                $re_data['sub_code'] = 'SYSTEMERROR';
                $re_data['sub_msg'] = $tra_data_arr['message'];
            }


            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage(). $exception->getLine();

            return $this->return_data($re_data);
        }

    }


    //退款接口
    public function refund(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }
            $device_no = $data['device_no'];
            $InCodeList = InCodeList::where('device_id', $device_no)
                ->select('merchant_id', 'store_id')
                ->first();
            //需要处理
            $merchant_id = $InCodeList->merchant_id;
            $store_id = $InCodeList->store_id;


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'sub_code' => '',
                'sub_msg' => '',
                'return_fee' => $data['refund_fee'],
                'out_return_no' => '',
                'time' => '',
            ];


            $out_trade_no = isset($data['refund_code']) ? $data['refund_code'] : $data['pp_trade_no'];


            $data_re = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => number_format($data['refund_fee'] / 100, 2, '.', ''),
            ];

            $refund_obj = new OrderController();
            $return = $refund_obj->refund_public($data_re);
            $tra_data_arr = json_decode($return, true);



            if ($tra_data_arr['status'] != 1) {
                $re_data['code'] = 'FAIL';
                $re_data['msg'] = $tra_data_arr['message'];
                return $this->return_data($re_data);
            }

            $re_data['sub_code'] = 'SUCCESS';
            $re_data['sub_msg'] = '退款成功';
            $re_data['out_return_no'] = isset($tra_data_arr['data']['refund_no']) ? $tra_data_arr['data']['refund_no'] : "";
            $re_data['time'] = date('Y-m-d H:i:s', time());

            //意锐
            $up_data = [
                'pay_status' => '3',
                'time_end' => date('YmdHis', time())
            ];


            InOrder::where('out_trade_no', $tra_data_arr['data']['out_trade_no'])
                ->where('store_id', $store_id)
                ->update($up_data);

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


    //撤销接口
    public function cancel(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'sub_code' => 'SUCCESS',
                'sub_msg' => '撤销订单号成功',
            ];

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


    //核销接口
    public function consume(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'sub_code' => 'SUCCESS',
                'sub_msg' => '核销成功',
            ];

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


    //键盘查账接口
    public function device_order(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'total_pay_amt' => '0',
                'total_pay_count' => '0',
            ];

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


    //账单接口
    public function order_query_count(Request $request)
    {
        try {


            //获取请求参数
            $data = $request->getContent();


            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }
            $time_start = date('Y-m-d H:i:s', strtotime($data['bill_begin_time']));
            $time_end = date('Y-m-d H:i:s', strtotime($data['bill_end_time']));

//            //限制时间
//            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
//            $day = 7;
//            if ($date > $day) {
//                $re_data['code'] = 'FAIL';
//                $re_data['msg'] = 'time >7 days';
//                return $this->return_data($re_data);
//
//            }

            $where = [];
            $device_no = $data['device_no'];
            $InCodeList = InCodeList::where('device_id', $device_no)
                ->select('config_id', 'store_id', 'merchant_id')
                ->first();
            //需要处理
            $config_id = $InCodeList->config_id;
            $store_id = $InCodeList->store_id;
            $merchant_id = $InCodeList->merchant_id;

            if ($time_start) {
                $where[] = ['created_at', '>=', $time_start];
            }
            if ($time_end) {
                $where[] = ['created_at', '<=', $time_end];
            }

            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }


            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 2;
            $now_time = date('Y-m-d H:i:s', time());
            $end = date('Y-m-d 22:00:00', time());
            if ($now_time > $end) {
                $day = 31;
            }

            if ($date > $day) {

                $time_start_s = date('Y-m-d 00:00:00', time());
                $time_start_e = date('Y-m-d 23:59:59', time());

                $time_start = $time_start_s;
                $time_end = $time_start_e;

            }

            //跨天操作
            $time_start_db = date('Ymd', strtotime($time_start));
            $time_end_db = date('Ymd', strtotime($time_end));;
            $is_ct_time=0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time=1;
            }


            $day = date('Ymd', strtotime($time_end));
            $table = 'orders_' . $day;

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                    } else {
                        $obj = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj = DB::table('order_items');

                        } else {
                            $obj = DB::table('orders');
                        }
                    }
                }
            }



            $order_data = $obj->where($where)
                ->whereIn('pay_status', [1, 6, 3])//成功+退款
                ->where('merchant_id', $merchant_id)
                ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


            $refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                ->where($where)
                ->select('refund_amount');


            $total_amount = $order_data->sum('total_amount');//交易金额
            $total_count = '' . count($order_data->get()) . '';
            $refund_amount = $refund_obj->sum('refund_amount');//退款金额
            $refund_count = count($refund_obj->get());

            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'total_pay_amt' => number_format($total_amount * 100, 0, '.', ''),
                'total_pay_count' => "" . $total_count . "",
                'total_refund_amt' => number_format($refund_amount * 100, 0, '.', ''),
                'total_refund_count' => "" . $refund_count . "",
            ];

            //返回交易明细
            if ($data['details'] == 'TRUE') {

                //账单明细
                $InOrder = InOrder::where($where)
                    ->where('merchant_id', $merchant_id)
                    ->get();
                $transaction_detail = $InOrder;


                if (env('DB_D1_HOST')) {
                    //有没有跨天
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj1 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj1 = DB::connection("mysql_d1")->table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj1 = DB::connection("mysql_d1")->table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj1 = DB::connection("mysql_d1")->table('order_items');

                            } else {
                                $obj1 = DB::connection("mysql_d1")->table('orders');
                            }
                        }
                    }
                } else {
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj1 = DB::table('order_items');
                        } else {
                            $obj1 = DB::table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj1 = DB::table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj1 = DB::table('order_items');

                            } else {
                                $obj1 = DB::table('orders');
                            }
                        }
                    }
                }



                //支付宝
                $alipay_order_data = $obj1->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'alipay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $alipay_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'alipay')
                    ->where($where)
                    ->select('refund_amount');

                if (env('DB_D1_HOST')) {
                    //有没有跨天
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj2 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj2 = DB::connection("mysql_d1")->table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj2 = DB::connection("mysql_d1")->table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj2 = DB::connection("mysql_d1")->table('order_items');

                            } else {
                                $obj2 = DB::connection("mysql_d1")->table('orders');
                            }
                        }
                    }
                } else {
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj2 = DB::table('order_items');
                        } else {
                            $obj2 = DB::table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj2 = DB::table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj2 = DB::table('order_items');

                            } else {
                                $obj2 = DB::table('orders');
                            }
                        }
                    }
                }


                //微信
                $weixin_order_data = $obj2->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'weixin')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $weixin_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'weixin')
                    ->where($where)
                    ->select('refund_amount');



                if (env('DB_D1_HOST')) {
                    //有没有跨天
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj3 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj3 = DB::connection("mysql_d1")->table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj3 = DB::connection("mysql_d1")->table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj3 = DB::connection("mysql_d1")->table('order_items');

                            } else {
                                $obj3 = DB::connection("mysql_d1")->table('orders');
                            }
                        }
                    }
                } else {
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj3 = DB::table('order_items');
                        } else {
                            $obj3 = DB::table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj3 = DB::table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj3 = DB::table('order_items');

                            } else {
                                $obj3 = DB::table('orders');
                            }
                        }
                    }
                }

                //京东
                $jd_order_data =$obj3->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'jd')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $jd_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'jd')
                    ->where($where)
                    ->select('refund_amount');
                //银联扫码

                if (env('DB_D1_HOST')) {
                    //有没有跨天
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj4 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj4 = DB::connection("mysql_d1")->table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj4 = DB::connection("mysql_d1")->table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                                $obj4 = DB::connection("mysql_d1")->table('order_items');

                            } else {
                                $obj4 = DB::connection("mysql_d1")->table('orders');
                            }
                        }
                    }
                } else {
                    if ($is_ct_time) {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj4 = DB::table('order_items');
                        } else {
                            $obj4 = DB::table('orders');
                        }
                    } else {

                        if (Schema::hasTable($table)) {
                            $obj4 = DB::table($table);

                        } else {
                            if (Schema::hasTable('order_items')&&$time_start>"2019-12-21 00:00:00") {
                                $obj4 = DB::table('order_items');

                            } else {
                                $obj4 = DB::table('orders');
                            }
                        }
                    }
                }
                $unqr_order_data =$obj4->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->whereNotIn('ways_type', [6005, 8005, 13005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $unqr_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->whereNotIn('type', [6005, 8005, 13005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where($where)
                    ->select('refund_amount');

                //支付宝
                $alipay_total_amount = $alipay_order_data->sum('total_amount');//交易金额
                $alipay_refund_amount = $alipay_refund_obj->sum('refund_amount');//退款金额
                $alipay_total_count = '' . count($alipay_order_data->get()) . '';
                $alipay_refund_count = count($alipay_refund_obj->get());


                //微信
                $weixin_total_amount = $weixin_order_data->sum('total_amount');//交易金额
                $weixin_refund_amount = $weixin_refund_obj->sum('refund_amount');//退款金额
                $weixin_total_count = '' . count($weixin_order_data->get()) . '';
                $weixin_refund_count = count($weixin_refund_obj->get());


                //京东
                $jd_total_amount = $jd_order_data->sum('total_amount');//交易金额
                $jd_refund_amount = $jd_refund_obj->sum('refund_amount');//退款金额
                $jd_total_count = '' . count($jd_order_data->get()) . '';
                $jd_refund_count = count($jd_refund_obj->get());


                //银联扫码
                $unqr_total_amount = $unqr_order_data->sum('total_amount');//交易金额
                $unqr_refund_amount = $unqr_refund_obj->sum('refund_amount');//退款金额
                $unqr_total_count = '' . count($unqr_order_data->get()) . '';
                $unqr_refund_count = count($unqr_refund_obj->get());


                //支付汇总
                $pay_summary = [
                    [
                        'pay_type' => 'ALIPAY',
                        'total_pay_count' => $alipay_total_count,
                        'total_pay_fee' => number_format($alipay_total_amount * 100, 0, '.', ''),
                    ],

                    [
                        'pay_type' => 'WXPAY',
                        'total_pay_count' => $weixin_total_count,
                        'total_pay_fee' => number_format($weixin_total_amount * 100, 0, '.', ''),
                    ], [
                        'pay_type' => 'JDPAY',
                        'total_pay_count' => $jd_total_count,
                        'total_pay_fee' => number_format($jd_total_amount * 100, 0, '.', ''),
                    ], [
                        'pay_type' => 'UNIONPAY',
                        'total_pay_count' => $unqr_total_count,
                        'total_pay_fee' => number_format($unqr_total_amount * 100, 0, '.', ''),
                    ]

                ];
                //退款汇总
                $return_summary = [
                    [
                        'pay_type' => 'ALIPAY',
                        'total_refund_count' => $alipay_refund_count,
                        'total_refund_fee' => number_format($alipay_refund_amount * 100, 0, '.', ''),
                    ],

                    [
                        'pay_type' => 'WXPAY',
                        'total_refund_count' => $weixin_refund_count,
                        'total_refund_fee' => number_format($weixin_refund_amount * 100, 0, '.', ''),
                    ], [
                        'pay_type' => 'JDPAY',
                        'total_refund_count' => $jd_refund_count,
                        'total_refund_fee' => number_format($jd_refund_amount * 100, 0, '.', ''),
                    ], [
                        'pay_type' => 'UNIONPAY',
                        'total_refund_count' => $unqr_refund_count,
                        'total_refund_fee' => number_format($unqr_refund_amount * 100, 0, '.', ''),
                    ]
                ];


                $re_data['transaction_detail'] = json_encode($transaction_detail);
                $re_data['pay_summary'] = json_encode($pay_summary);
                $re_data['refund_summary'] = json_encode($return_summary);
            }


            return $this->return_json_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


    //获取门店商户信息
    public function query_store(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }

            $device_no = $data['device_no'];

            $InCodeList = InCodeList::where('device_id', $device_no)
                ->select('merchant_id', 'store_id')
                ->first();


            if ($InCodeList) {
                $re_data['code'] = 'FAIL';
                $re_data['msg'] = 'code is use';
                return $this->return_data($re_data);
            }

            //需要处理
            $store = Store::where('store_id', $InCodeList->store_id)
                ->select('store_short_name')
                ->first();
            $Merchant = Merchant::where('id', $InCodeList->merchant_id)
                ->select('name')
                ->first();


            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '返回成功',
                'store_name' => $store->store_short_name,
                'merchant_name' => $Merchant->name,
            ];

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


    //登录接口
    public function login(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }
            $device_no = $data['deviceid'];
            $username = $data['username'];

            $Merchant = Merchant::where('phone', $username)
                ->select('config_id', 'id')
                ->first();


            if (!$Merchant) {
                //公共返回参数
                $re_data = [
                    'code' => 'FAIL',
                    'msg' => 'phone is errors',
                    'sub_code' => '0001',
                ];

                return $this->return_data($re_data);
            }

            $MerchantStore = MerchantStore::where('merchant_id', $Merchant->id)
                ->select('store_id')
                ->first();

            $config_id = $Merchant->config_id;
            $store_id = $MerchantStore->store_id;
            $merchant_id = $Merchant->id;


            //登录的账户密码和


            $InCodeList = InCodeList::where('device_id', $device_no)
                ->select('id', 'store_id', 'merchant_id')
                ->first();
            if ($InCodeList) {
                $InCodeList_store_id = $InCodeList->store_id;
                $InCodeList_merchant_id = $InCodeList->merchant_id;

                //激活码不能重复绑定
                if ($InCodeList_store_id != $store_id) {
                    $re_data['code'] = 'FAIL';
                    $re_data['sub_code'] = '0001';
                    $re_data['msg'] = 'Activation codes are used many times';
                    return $this->return_data($re_data);
                }

                //激活码不能重复绑定
                if ($merchant_id != $InCodeList_merchant_id) {
                    $re_data['code'] = 'FAIL';
                    $re_data['sub_code'] = '0001';
                    $re_data['msg'] = 'Activation codes are used many times';
                    return $this->return_data($re_data);
                }
            }


            $insert = [
                'config_id' => $config_id,
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                "device_id" => $device_no,
            ];
            if ($InCodeList) {
                InCodeList::where('device_id', $device_no)->update($insert);
            } else {
                InCodeList::create($insert);
            }

            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '登录成功',
                'sub_code' => '0000',
            ];

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['sub_code'] = '0001';
            $re_data['msg'] = $exception->getMessage() . $exception->getLine();
            return $this->return_data($re_data);
        }


    }


    //退出接口
    public function login_out(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['code'] == 'FAIL') {
                return $this->return_data($check);
            }

            //公共返回参数
            $re_data = [
                'code' => 'SUCCESS',
                'msg' => '退出成功',
                'sub_code' => '0000',
            ];

            return $this->return_data($re_data);


        } catch (\Exception $exception) {
            $re_data['code'] = 'FAIL';
            $re_data['sub_code'] = '0001';
            $re_data['msg'] = $exception->getMessage();
            return $this->return_data($re_data);
        }


    }


}
